package com.zbiti.anvil.basic.admin.gateway.sso.sso1;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * RSA加解密工具类
 *
 * @author Fanyc
 * @date 2024/9/3 14:54
 */
public final class RSAUtil {

    /**
     * 加密算法：RSA
     */
    public static final String ALGORITHM_RSA = "RSA";

    /**
     * 得到私钥
     *
     * @param privateKey 密钥字符串（经过base64编码）
     * @return 私钥对象
     * @throws NoSuchAlgorithmException 算法异常
     * @throws InvalidKeySpecException  key异常
     */
    private static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
    }

    /**
     * 加密
     *
     * @param data      要加密数据
     * @param key       公钥或者私钥
     * @param bitLength 位长
     * @return 密文
     */
    private static String encrypt(String data, Key key, int bitLength) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_RSA);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(StandardCharsets.UTF_8), bitLength));
        } catch (Exception e) {
            //throw new BusinessException("加密异常：{}", e.getMessage(), e);
            throw new RuntimeException("加密异常：{}", e);
        }
    }

    /**
     * 私钥加密
     *
     * @param data       明文
     * @param privateKey 私钥密钥字符串（base64编码）
     * @return 密文
     */
    public static String privateEncrypt(String data, String privateKey) throws InvalidKeySpecException, NoSuchAlgorithmException {
        return privateEncrypt(data, getPrivateKey(privateKey));
    }

    /**
     * 私钥加密
     *
     * @param data       明文
     * @param privateKey 私钥
     * @return 密文
     */
    private static String privateEncrypt(String data, RSAPrivateKey privateKey) {
        return encrypt(data, privateKey, privateKey.getModulus().bitLength());
    }

    /**
     * RSA解码解析
     */
    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        int maxBlock = 0;
        if (opmode == Cipher.DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        byte[] resultDatas;
        try {
            while (datas.length > offSet) {
                if (datas.length - offSet > maxBlock) {
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
            resultDatas = out.toByteArray();
        } catch (Exception e) {
            //throw new BusinessException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        } finally {
            try {
                out.close();
            } catch (IOException ignored) {
            }
        }
        return resultDatas;
    }
}